#include "linkstack.h"

stack *init_stack(void)
{
    stack *s = calloc(1, sizeof(stack));
    if(s != NULL)
    {
        s->size = 0;
        s->top  = NULL;
    }
    return s;
}

list new_node(int num)
{
    list newnode = calloc(1, sizeof(node));
    if(newnode != NULL)
    {
        newnode->data = num;
        newnode->next = NULL;
    }
    return newnode;
}

bool push(stack *s, list newnode)
{
    newnode->next = s->top;
    s->top = newnode;
    s->size++;
    return true;
}

bool is_empty(stack *s)
{
    return s->size == 0;
}

bool pop(stack *s, node **k)
{
    if(is_empty(s))
        return false;
    
    *k = s->top;
    s->top = s->top->next;
    (*k)->next = NULL;

    s->size--;
    return true;
}

void destroy_init(stack *s)
{
    // 逐个释放单链表的各个节点
    for(list p=s->top, n; p!=NULL; p=n)
    {
        n = p->next;
        free(p);
    }
    s->top = NULL;
    s->size = 0;
}

void destroy(stack *s)
{
    destroy_init(s);
    free(s);
}